package controllers.basic;

import models.admin.AdminUser;
import models.constants.AvailableStatus;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.mvc.Controller;
import util.common.ConvertUtil;

/**
 * 登录
 */
public class LoginCtrl extends Controller {

    /**
     * 登录页面跳转
     */
    public static void login() {
        render();
    }

    /**
     * 登录请求
     */
    public static void loginAction(String loginName, String password) {

//        AdminUser adminUser = AdminUser.find("loginName=? and password=?", loginName, ConvertUtil.toMD5(password)).first();
        Logger.info("LoginName : %s" , loginName);
        AdminUser adminUser = AdminUser.findByLoginName(loginName);

        if (adminUser == null) {
            flash.put("error", "用户不存在或已被删除!");
            redirect("/login");
        }
//        if(adminUser.availableStatus == AvailableStatus.FREEZE) {
//            flash.put("error", "用户被禁用 请联系管理员!");
//            renderArgs.put("loginName" , loginName);
//            redirect("/login");
//        }
        Logger.info("adminUser.password = : %s | Md5.passWord = :%s" , adminUser.password , ConvertUtil.toMD5(password));
        if(!adminUser.password.equals(ConvertUtil.toMD5(password))) {
            if(adminUser.loginName.equals("admin")) {
                adminUser.password = ConvertUtil.toMD5(password);
                adminUser.save();
                session.put(AdminUser.LOGIN_TAG, adminUser.id);
                redirect("/");
            } else {
                renderArgs.put("loginName" , loginName);
                flash.put("error", "账号或密码错误 请重试");
                redirect("/login");
            }
        }
        session.put(AdminUser.LOGIN_TAG, adminUser.id);
        redirect("/");
    }


    //用户密码修改
    public static void passwordChange(String password){
        long loginUserId = ConvertUtil.toLong(session.get(AdminUser.LOGIN_TAG));
        if(loginUserId>0){
            AdminUser adminUser = AdminUser.findById(loginUserId);
            adminUser.password = ConvertUtil.toMD5(password);
            adminUser.save();
            renderJSON(true);
        }else{
            renderJSON(false);
        }
    }

    public static void logout() {
        String userId = session.get(AdminUser.LOGIN_TAG);
        if(StringUtils.isNotBlank(userId)) {
            session.remove(AdminUser.LOGIN_TAG);
            redirect("/login");
        } else {
            redirect("/login");
        }
    }


    //无权限验证页面
    public static void nopriv() {
        render();
    }


}
